<?php
include_once('inc/functions.inc.php');

if (!isEmpty(getParam('operation'))) {
    $db = DbManager::getMe();
    switch (getParam('operation')) {
        case 'filtro': {
                fntAcademicoCobrosCierreFiltro($db);
                break;
            }
        case 'secciones': {
                fntAcademicoCobrosCierreFiltroSecciones($db);
                break;
            }
        case 'contenido': {
                fntAcademicoCobrosCierreContenido($db);
                break;
            }
        case 'contenidoDetalle': {
                fntAcademicoCobrosCierreContenidoDetalle($db);
                break;
            }
        case 'contenidoPartida': {
                fntAcademicoCobrosCierreContenidoPartida($db);
                break;
            }
        case 's': {
                fntAcademicoCobrosCierreGrabar($db);
                break;
            }
    }
    die();
}

function fntAcademicoCobrosCierreContenido($db) {
    $strQuery = "";
    ?>
    <div style="width: 800px;">
        <div style="float: left; width: 100%;" class="dttb">
            <table >
                <thead>
                    <tr>
                        <th><div style="width: 100px;">Fecha Cobro</div></th>
                        <th><div style="width: 80px;">Nota Banco</div> </th>
                        <th><div style="width: 200px;">Nombre</div></th>
                        <th><div style="width: 60px;">Forma Pago</div></th>
                        <th><div style="width: 60px;">Total (L)</div></th>
                        <th><div style="width: 20px;"><input  type="checkbox" name="checkAll" id="checkAll" />
                            <label for="checkAll"></label></div></th>
                    </tr>
                </thead>
            </table>
        </div>
        <div style="float: left; height: 200px; overflow-y: scroll; margin-bottom: 5px; width: 100%;" class="dttb">
            <table>
                <tbody>
                    <?php
                    $usr = $_SESSION[USUARIO]["usuario"];
                    $strQuery = " select pagos.*,IF(ISNULL(formapago.TIPOSPAGO),'EFECTIVO',formapago.TIPOSPAGO) fPago,
                        formapago.NO_RECIBO,formapago.FECPAGO from (                          
select CONCAT(e.FIRST_NAME,' ',e.LAST_NAME,' - STD/PF') ESTUDIANTE,  p.ID,p.FECHA, sum(d.MONTO) TOTAL_PAGO,
        GROUP_CONCAT(d.FK_COBRO_ID) COBROS_CANCELADOS       
      from cllg_academico_pagos p, cllg_academico_pagos_detail d,
       cllg_academico_cobros c, cllg_student e       
      where (ISNULL(p.USUARIO_PAGO) OR p.USUARIO_PAGO='$usr' ) and p.ESTADO='EMITIDO' and d.FK_PAGO_ID=p.ID and d.FK_COBRO_ID=c.ID and c.FK_ESTUDIANTE=e.ID
         and c.TIPO='ESTUDIANTE' 
      group by e.ID,p.ID,p.FECHA) pagos
      left join 
        (select pf.FECHA FECPAGO, pf.FK_PAGO_ID,pf.NO_RECIBO, GROUP_CONCAT(pf.TIPO) TIPOSPAGO,
            sum(pf.MONTO) TOTALPAGO
         from cllg_academico_pagos_formas pf group by pf.FK_PAGO_ID,pf.NO_RECIBO) as formapago
            on pagos.ID=formapago.FK_PAGO_ID
union all
select pagos.*,IF(ISNULL(formapago.TIPOSPAGO),'EFECTIVO',formapago.TIPOSPAGO) fPago,formapago.NO_RECIBO,formapago.FECPAGO from (                          
select CONCAT(e.RAZON_SOCIAL,' - BNF') ESTUDIANTE,p.ID,p.FECHA, sum(d.MONTO) TOTAL_PAGO,
        GROUP_CONCAT(d.FK_COBRO_ID) COBROS_CANCELADOS       
      from cllg_academico_pagos p, cllg_academico_pagos_detail d,
       cllg_academico_cobros c, cllg_benefactor e       
      where (ISNULL(p.USUARIO_PAGO) OR p.USUARIO_PAGO='$usr' ) AND p.ESTADO='EMITIDO' and d.FK_PAGO_ID=p.ID and d.FK_COBRO_ID=c.ID and c.FK_ESTUDIANTE=e.ID
         and c.TIPO='BENEFACTOR' 
      group by e.ID,p.ID,p.FECHA) pagos
      left join (select pf.FECHA FECPAGO,pf.FK_PAGO_ID,pf.NO_RECIBO, GROUP_CONCAT(pf.TIPO) TIPOSPAGO,sum(pf.MONTO) TOTALPAGO
          from cllg_academico_pagos_formas pf group by pf.FK_PAGO_ID,pf.NO_RECIBO) as formapago
      on pagos.ID=formapago.FK_PAGO_ID";
                    $cobrosPagos = array();
                    $qTMP = $db->query($strQuery);
                    while ($rTMP = $db->fetch_array($qTMP)) {
                        $cobrosPagos[$rTMP["ID"]] = $rTMP["COBROS_CANCELADOS"];
                        ?>
                        <tr>
                            <td align="left" > 
                                <div style="width: 100px;">
                                    <?php print date("d/m/Y", strtotime($rTMP["FECPAGO"])); ?></div></td>
                            <td align="left" ><div style="width: 80px;">
                                    <?php print htmlentities($rTMP["NO_RECIBO"]); ?></div>
                            </td>
                            <td align="left" ><div style="width: 200px;">
                                    <?php print htmlentities($rTMP["ESTUDIANTE"]); ?></div>
                            </td>
                            <td align="right" ><div style="width: 60px;">
                                    <?php print $rTMP["fPago"]; ?>
                                </div>
                            </td>
                            <td align="right" ><div style="width: 60px;">
                                    <?php print number_format($rTMP["TOTAL_PAGO"], 2); ?>&nbsp;&nbsp;
                                    <input type="hidden" name="montoPagoID_<?php print $rTMP["ID"]; ?>" id="montoPagoID_<?php print $rTMP["ID"]; ?>" value="<?php print $rTMP["TOTAL_PAGO"]; ?>" />
                                </div>
                            </td>
                            <td><div style="width: 20px;">
                                    <input type="checkbox" name="chkPagoID_<?php print $rTMP["ID"]; ?>" value="<?php print $rTMP["ID"]; ?>" /></div>
                            </td>
                        </tr>
                        <?php
                    }
                    addSessionVar("COBROSPAGO", $cobrosPagos, true);
                    $db->free_result($qTMP);
                    ?>
                </tbody>                
            </table>
        </div>
        <div style="width: 100%; float: left; margin-bottom: 5px;" class="dttb">
            <table>
                <tfoot>
                    <tr>
                        <th align="right" ><div style="width: 100px;">&nbsp;</div></th>
                        <th align="right" ><div style="width: 100px;">&nbsp;</div></th>
                        <th align="right" ><div style="width: 215px;"><b>Total General&nbsp;&nbsp;</b></div></th>
                        <th align="left" ><div style="width: 70px;"></div>
                        <th align="left" ><div style="width: 70px;">
                            <input type="text" name="txtAcademicoCobrosCierreTotal" value="0.00"
                                   style="width: 96%; text-align: right; border: none; background-color: transparent" readonly="readonly" />
                        </div>
                        </th>
                        <th  ><div style="width: 25px;">&nbsp;</div></th>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
    <div id="divAcademicoCobrosCierreContenidoDetalle" style="width: 1000px; float: left; background: white;">&nbsp;</div>
    <script type="text/javascript" >
        /*patch checkall cierres*/
        $("#checkAll").click(function(){
            $("[name*='chkPagoID_']").attr('checked',$(this).attr('checked'));
            fntAcademicoCobrosCierreContenidoDetalle();
            fntAcademicoCobrosCierreTotal();
        });
        /*end patch*/
        $(function() {
            $("[name*='chkPagoID_']").click( function() {
                fntAcademicoCobrosCierreContenidoDetalle();
                fntAcademicoCobrosCierreTotal();
            });
        });
        function fntAcademicoCobrosCierreTotal() {
            sinTotal = 0;            
            $("input[name*='chkPagoID_']").each( function() {
                if( $(this).attr("checked") ) {
                    sinTotal += $("#montoPagoID_"+$(this).val()).val() * 1;
                }else{ //si uno esta negativo desactiva ALL
                    $("#checkAll").attr("checked",false); 
                }
            });
            $("input[name='txtAcademicoCobrosCierreTotal']").val(sinTotal);
        }
    </script>
    <?php
}

function fntAcademicoCobrosCierreContenidoDetalle($db) {
    $strPago = "";
    reset($_POST);
    while ($arrPost = each($_POST)) {
        $arrExplode = explode("_", $arrPost["key"]);
        if ($arrExplode[0] == "chkPagoID") {
            $strPago .= ( empty($strPago)) ? "" : ",";
            $strPago .= $arrExplode[1];
        }
    }
    ?>
    <div class="dttb">
        <table width="50%" cellpadding="2" cellspacing="2" border="0" style="border-collapse: collapse;" id="tblAcademicoCobrosCierreContenidoDetalle">
            <!--<tr> Ya no es necesario mostrar nuevamente el listado 
                <td width="34%"  ><b>Fecha</b></td>
                <td width="34%"  ><b>No. Documento</b></td>
                <td width="33%"  ><b>Tipo de Pago</b></td>
                <td width="33%"  ><b>Valor (L)</b></td>
            </tr>-->
            <?php
            $strQuery = "SELECT cllg_bnc_banco.NOMBRE AS BANCO,
                            cllg_bnc_cuenta.NUMERO, 
                            cllg_bnc_cuenta.CUENTA, 
                            IF(cllg_bnc_cuenta_chequeras.ID IS NULL,' ( Sin chequera habilitada ) ','') AS HABILITADA 
                    FROM    cllg_bnc_banco, 
                            cllg_bnc_cuenta
                            LEFT JOIN cllg_bnc_cuenta_chequeras 
                            ON cllg_bnc_cuenta.NUMERO = cllg_bnc_cuenta_chequeras.FK_CUENTA 
                                AND cllg_bnc_cuenta_chequeras.ESTADO = 1
                    WHERE   cllg_bnc_banco.ID = cllg_bnc_cuenta.FK_BANCO
                    AND     cllg_bnc_cuenta.ESTADO = '1' 
                    ORDER   BY cllg_bnc_cuenta.NUMERO";
            $qTMP = $db->query($strQuery);
            $intNumRows = $db->num_rows;

            $arrCuentas = array();
            if ($intNumRows > 0) {
                while ($rTMP = $db->fetch_array($qTMP)) {
                    $arrCuentas[$rTMP["BANCO"]][$rTMP["NUMERO"]] = $rTMP["CUENTA"];
                }
            }
            $sinTotal = 0;
            $db->free_result($qTMP);
            if (!empty($strPago)) { 
                $strQuery = "select sum(IF(ISNULL(formapago.MONTO),p.TOTAL,formapago.MONTO)) MONTO 
                        from cllg_academico_pagos p left join (
                        SELECT * from cllg_academico_pagos_formas pf 
                            where pf.FK_PAGO_ID IN({$strPago})) formapago 
                            on p.ID=formapago.FK_PAGO_ID
                        where p.ID IN({$strPago}) ";
                        $qTMP = $db->query($strQuery);
                while ($rTMP = $db->fetch_array($qTMP)) {
                    $sinTotal += $rTMP["MONTO"];
                }
            }
            /*  //YA NO ES NECESARIO HACER EL RECORRIDO
                $sinTotal = 0;
                $strQuery = "select p.ID,IF(ISNULL(formapago.NO_RECIBO),'NA',formapago.NO_RECIBO) NO_RECIBO,
                    IF(ISNULL(formapago.TIPO),'EFECTIVO',formapago.TIPO) TIPO,
                    IF(ISNULL(formapago.MONTO),p.TOTAL,formapago.MONTO) MONTO,formapago.FECHA from cllg_academico_pagos p left join (
                SELECT * from cllg_academico_pagos_formas pf 
                where pf.FK_PAGO_ID IN({$strPago})) formapago 
                on p.ID=formapago.FK_PAGO_ID
                where p.ID IN({$strPago}) ";

                $qTMP = $db->query($strQuery);
                while ($rTMP = $db->fetch_array($qTMP)) {

                    $sinTotal += $rTMP["MONTO"];
                    ?>
                    <tr>
                        <td width="25%"  ><?php print date("d/m/Y", strtotime($rTMP["FECHA"])); ?></td>
                        <td width="25%"  ><?php print $rTMP["NO_RECIBO"]; ?></td>
                        <td width="25%"  ><?php print $rTMP["TIPO"]; ?></td>
                        <td width="25%" align="right" ><?php print number_format($rTMP["MONTO"], 2); ?>&nbsp;&nbsp;</td>
                    </tr>
                    <?php
                }
                $db->free_result($qTMP);
            }*/
            ?>
            <tr>
                <td height="41">
                    <input type="hidden" name="hdnMonto_1" value="<?php print $sinTotal; ?>" />
                    <input type="hidden" name="hdnPagos_1" value="<?php print $strPago; ?>" />
                    <b>Cuenta Bancaria</b><script type="text/javascript" >
                        $(function() {
                            $("select[name='sltCuenta_1']").change( function () {
                                fntAcademicoCobrosCierreContenidoPartida();
                            });
                        });
                    </script>
                </td>
                <td height="41"><select name="sltCuenta_1" style="width: 165px;">
                        <option value="0"></option>
                        <?php
                        reset($arrCuentas);
                        while ($arrTMP = each($arrCuentas)) {
                            ?>
                            <optgroup label="<?php print $arrTMP["key"]; ?>">
                                <?php
                                while ($arrTMP1 = each($arrTMP["value"])) {
                                    ?>
                                    <option value="<?php print $arrTMP1["key"]; ?>"><?php print $arrTMP1["value"]; ?></option>
                                    <?php
                                }
                                ?>
                            </optgroup>
                            <?php
                        }
                        ?>
                    </select></td>
                <td height="41">&nbsp;</td>
            </tr>
            <tr>
                <td><label for="hdnAcademicoCobrosCierreFecha"><strong>Fecha Deposito:</strong></label></td>
                <td>
                    <input type="text" name="hdnAcademicoCobrosCierreFecha" id="hdnAcademicoCobrosCierreFecha" /></td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td><label for="hdnAcademicoCobrosCierreNotaBanco"><strong>Nota Banco:</strong></label></td>
                <td>
                    <input type="text" name="hdnAcademicoCobrosCierreNotaBanco" id="hdnAcademicoCobrosCierreNotaBanco" /></td>
                <td>&nbsp;</td>
            </tr>
        </table>
    </div>
    <script type="text/javascript">
        $("input[name='hdnAcademicoCobrosCierreFecha']").datepicker({
            changeMonth: true,
            changeYear: true,
            monthNamesShort: ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'],
            dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'],
            dateFormat: 'dd-mm-yy'
        });
    </script>
    <?php
}

function fntAcademicoCobrosCierreContenidoPartida($db) {
    $intEmpresa = 1;
    $arrInfo = array();
    $arrCuentasBancos = array();
    $arrAjuste = array();
    $cobros = getSessionVar("COBROSPAGO", true);
    $cobrosPorPago = "";
    reset($_POST);
    while ($arrPost = each($_POST)) {
        $arrExplode = explode("_", $arrPost["key"]);
        if ($arrExplode[0] == "chkPagoID") {
            /* $strCobros .= ( empty($strCobros)) ? "" : ",";
              $strCobros .= $_POST["hdnCobroID_{$arrExplode[1]}"]; */
            $cobrosPorPago .= ( empty($cobrosPorPago)) ? "" : ",";
            $cobrosPorPago.=$cobros[$arrExplode[1]];
        }
    }
    ?>
    <script type="text/javascript" language="javascript">
        var intEmpresa = 1;
    </script> 
    <?php
    $usr = $_SESSION[USUARIO]["usuario"];
    $strQuery ="SELECT cllg_academico_pagos_detail.ID,cllg_academico_cobros.ID,cllg_academico_cobros.VALOR, cllg_academico_pagos_detail.MONTO VALORPAGO, DATE_FORMAT(cllg_academico_cobros.FECHA, '%d-%m-%Y') AS FECHA, 
cllg_academico_cargos_detail.DESCRIPCION, cllg_academico_cargos_detail.CTA_COBRAR, cllg_academico_cargos_detail.CTA_INGRESOS 
FROM cllg_academico_cobros, cllg_academico_cargos_detail,cllg_academico_pagos_detail,cllg_academico_pagos p
WHERE cllg_academico_cobros.ESTADO IN ('PAGADO','PAGADOPARCIAL') 
and cllg_academico_pagos_detail.FK_COBRO_ID=cllg_academico_cobros.ID
AND cllg_academico_cobros.FK_CARGO_DETAIL_ID = cllg_academico_cargos_detail.ID 
        AND cllg_academico_cobros.ID IN({$cobrosPorPago}) and cllg_academico_pagos_detail.FK_PAGO_ID=p.ID
        AND p.USUARIO_PAGO='$usr'";
    /*$strQuery = "SELECT  cllg_academico_cobros.ID, 
                        (cllg_academico_cobros.SALDO_ANT-cllg_academico_cobros.SALDO_ACT) VALORPAGO, 
                        DATE_FORMAT(cllg_academico_cobros.FECHA, '%d-%m-%Y') AS FECHA,
                        cllg_academico_cargos_detail.DESCRIPCION, 
                        cllg_academico_cargos_detail.CTA_COBRAR, cllg_academico_cargos_detail.CTA_INGRESOS     
                FROM    cllg_academico_cobros, 
                        cllg_academico_cargos_detail
                WHERE   cllg_academico_cobros.ESTADO IN ('PAGADO','PAGADOPARCIAL')
                AND     cllg_academico_cobros.FK_CARGO_DETAIL_ID = cllg_academico_cargos_detail.ID
                 AND cllg_academico_cobros.ID IN({$cobrosPorPago})";
//           echo $strQuery;*/
                
    $qTMP = $db->query($strQuery);
    $arrInfo = array("FECHA" => "", "VALOR" => "", "DESCRIPCION" => "");
    while ($rTMP = $db->fetch_array($qTMP)) {
        $arrInfo["FECHA"] = $rTMP["FECHA"];
        $arrInfo["VALOR"] += isset($rTMP["VALORPAGO"]) ? $rTMP["VALORPAGO"] : 0;
        $arrInfo["DESCRIPCION"] = $rTMP["DESCRIPCION"];

        $sinMonto = mround($rTMP["VALORPAGO"], 2);
        $strQuery1 = "SELECT *
                     FROM   cllg_contab_cuenta 
                     WHERE  fk_empresa = '{$intEmpresa}'
                     AND    codigo = '{$rTMP["CTA_COBRAR"]}'";
        $qTMP1 = $db->query($strQuery1);
        while ($rTMP1 = $db->fetch_array($qTMP1)) {
            if (!isset($arrAjuste["H" . $rTMP1["codigo"]])) {
                $arrAjuste["H" . $rTMP1["codigo"]]["codigo"] = $rTMP1["codigo"];
                $arrAjuste["H" . $rTMP1["codigo"]]["nombre"] = $rTMP1["nombre"];
                $arrAjuste["H" . $rTMP1["codigo"]]["tipo"] = "h";
                $arrAjuste["H" . $rTMP1["codigo"]]["monto"] = $sinMonto;
            } else {
                $arrAjuste["H" . $rTMP1["codigo"]]["monto"] += $sinMonto;
            }
        }
        $db->free_result($qTMP1);
    }
    $db->free_result($qTMP);


    reset($_POST);
    while ($arrTMP = each($_POST)) {
        $arrExplode = explode("_", $arrTMP["key"]);
        if ($arrExplode[0] == "sltCuenta") {
            $sinMonto = ( isset($_POST["hdnMonto_{$arrExplode[1]}"]) ) ? mround($_POST["hdnMonto_{$arrExplode[1]}"], 2) : 0;
            $strQuery = "SELECT  *
                        FROM    cllg_bnc_cuenta
                        WHERE   NUMERO  = '{$arrTMP["value"]}'";
            $qTMP = $db->query($strQuery);
            while ($rTMP = $db->fetch_array($qTMP)) {
                if (!isset($arrCuentasBancos[$rTMP["FK_CUENTA_CONTABLE"]])) {
                    $arrCuentasBancos[$rTMP["FK_CUENTA_CONTABLE"]]["cuenta"] = $rTMP["FK_CUENTA_CONTABLE"];
                    $arrCuentasBancos[$rTMP["FK_CUENTA_CONTABLE"]]["monto"] = $sinMonto;
                } else {
                    $arrCuentasBancos[$rTMP["FK_CUENTA_CONTABLE"]]["monto"] += $sinMonto;
                }
            }
            $db->free_result($qTMP);
        }
    }

    reset($arrCuentasBancos);
    while ($arrTMP = each($arrCuentasBancos)) {
        $strQuery = "SELECT *
                     FROM   cllg_contab_cuenta 
                     WHERE  fk_empresa = '{$intEmpresa}'
                     AND    codigo = '{$arrTMP["value"]["cuenta"]}'";
        $qTMP = $db->query($strQuery);
        while ($rTMP = $db->fetch_array($qTMP)) {
            $arrAjuste["D" . $rTMP["codigo"]]["codigo"] = $rTMP["codigo"];
            $arrAjuste["D" . $rTMP["codigo"]]["nombre"] = $rTMP["nombre"];
            $arrAjuste["D" . $rTMP["codigo"]]["tipo"] = "d";
            $arrAjuste["D" . $rTMP["codigo"]]["monto"] = $arrTMP["value"]["monto"];
        }
        $db->free_result($qTMP);
    }
    ?>
    <div style="width: 800px; float: left;">
        <div style="width: 800px; float: left;">&nbsp;</div>
        <div style="width: 800px; float: left; text-align: center;"><b>Distribución contable</b></div>
        <div style="width: 800px; float: left;">&nbsp;</div>
        <div style="width: 100px; float: left">&nbsp;</div>
        <div style="width: 600px; float: left;">
            <input type="hidden" name="hdnAcademicoCobrosCierreValor" value="<?php print $arrInfo["VALOR"]; ?>" />
            <input type="hidden" name="hdnAcademicoCobrosCierreMonto" value="<?php print $arrInfo["VALOR"]; ?>" />
            <input type="hidden" name="hdnAcademicoCobrosCierreConcepto1" value="<?php print $arrInfo["DESCRIPCION"]; ?>" />
            <b>Descripci&oacute;n</b><br />
            <textarea cols="" rows=""  name="hdnAcademicoCobrosCierreConcepto" style="width: 100%"><?php print $arrInfo["DESCRIPCION"]; ?></textarea>
        </div>
        <div style="width: 100px; float: left">&nbsp;</div>
        <div style="width: 800px; float: left">&nbsp;</div>
        <div style="width: 800px; height: auto; float: left; text-align: center;">
            <div id="frmPartidas-detalle" style="width: 800px; float: left;">
                <div style="float: left; width: 400px; height: 30px; border-bottom: 1px solid black;"><b>Cuenta</b></div>
                <div style="float: left; width: 200px; height: 30px; border-bottom: 1px solid black; text-align: center;"><b>Debe</b></div>
                <div style="float: left; width: 200px; height: 30px; border-bottom: 1px solid black; text-align: center;"><b>Haber</b></div>
                <div style="float: left; width: 400px; height: 10px;">&nbsp;</div>
                <div style="float: left; width: 200px; height: 10px;">&nbsp;</div>
                <div style="float: left; width: 200px; height: 10px;">&nbsp;</div>
            </div>
            <div id="frmPartidas-totales" style="width: 800px; float: left;">
                <div style="float: left; width: 400px; height: 10px; border-collapse: separate; border-bottom: 1px solid black;">&nbsp;</div>
                <div style="float: left; width: 200px; height: 10px; border-collapse: separate; border-bottom: 1px solid black;">&nbsp;</div>
                <div style="float: left; width: 200px; height: 10px; border-collapse: separate; border-bottom: 1px solid black;">&nbsp;</div>
                <div style="float: left; width: 400px; height: 30px; margin-top: 5px; text-align: right;"><b>Totales</b></div>
                <div style="float: left; width: 200px; height: 30px; margin-top: 5px;"><input type="text" name="txtTotalDebe" id="txtTotalDebe" value="" style="text-align: right;" readonly="readonly" /></div>
                <div style="float: left; width: 200px; height: 30px; margin-top: 5px;"><input type="text" name="txtTotalHaber" id="txtTotalHaber" value="" style="text-align: right;" readonly="readonly" /></div>
            </div>
        </div>
        <div style="width: 800px; height: 40px; float: left; text-align: center;">
            &nbsp;
        </div>
        <div style="width: 800px; height: 40px; float: left; text-align: center;">
            <button type="button" id="btnAcademicoCobrosCierreGrabar">Grabar</button>
        </div>
        <script type="text/javascript">
            $( function() {

                $("#btnAcademicoCobrosCierreGrabar").button({
                    icons: {
                        primary: "ui-icon-disk"
                    }
                }).click( function () {
                    fntAcademicoCobrosCierreGrabar();
                }).button( "disable" );

    <?php
    reset($arrAjuste);
    $i = 1;
    while ($arrTMP = each($arrAjuste)) {
        ?>
                    intCorrelativo = <?php print $i; ?>;
                    drawNewLine(intCorrelativo, "<?php print $arrTMP["value"]["codigo"]; ?>", "<?php print $arrTMP["value"]["nombre"]; ?>", "<?php print $arrTMP["value"]["tipo"]; ?>", "<?php print $arrTMP["value"]["monto"]; ?>" );
        <?php
        $i++;
    }
    ?>
            intCorrelativo = <?php print $i; ?>;
            drawNewLine(intCorrelativo);

        });
        </script>
    </div>
    <?php
}

function fntAcademicoCobrosCierreGrabar($db) {
    $empresa = 1;
    $valor = getParam("hdnAcademicoCobrosCierreValor");
    $arrfecha = explode("-", getParam("hdnAcademicoCobrosCierreFecha"));
    $fecha = $arrfecha[2] . "-" . $arrfecha[1] . "-" . $arrfecha[0];
    $concepto = getParam("hdnAcademicoCobrosCierreConcepto");
    $intPagos = getParam("hdnPagos_1");
    $strNotas = "";
    $cobros = getSessionVar("COBROSPAGO", true);
    $strQuery = "SELECT *
                 FROM   cllg_contab_ciclo 
                 WHERE  activo = '1' 
                 AND    fecha_inicio <= '{$fecha}' 
                 AND    fecha_fin >= '{$fecha}'
                 AND    total_activo > 0 
                 AND    total_pasivo > 0
                 AND    fk_empresa = '{$empresa}'";
    $qTMP = $db->query($strQuery);
    $intCicloCerrado = $db->num_rows;
    $db->free_result($qTMP);

    $strQuery = "SELECT *
                 FROM   cllg_contab_ciclo 
                 WHERE  activo = '1' 
                 AND    fecha_inicio <= '{$fecha}' 
                 AND    fecha_fin >= '{$fecha}'
                 AND    fk_empresa = '{$empresa}'";
    $qTMP = $db->query($strQuery);
    $intCicloCorrecto = $db->num_rows;
    $db->free_result($qTMP);

    if ($intCicloCerrado > 0) {
        ?>
        <div class="ui-widget" style="border: 0px solid white; width: 900px; height: auto; vertical-align: bottom;" >
            <div class="ui-state-error ui-corner-all" style="margin-top: 0px; padding: 0pt 0.7em; height: auto; width: 450px;">
                <p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: 0.3em;"></span>
                    No se puede ingresar partida en una fecha ya cerrada.</p>
            </div>
        </div>
        <br />
        <?php
    } else if ($intCicloCorrecto == 0) {
        ?>
        <div class="ui-widget" style="border: 0px solid white; width: 900px; height: auto; vertical-align: bottom;" >
            <div class="ui-state-error ui-corner-all" style="margin-top: 0px; padding: 0pt 0.7em; height: auto; width: 450px;">
                <p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: 0.3em;"></span>
                    La fecha de la partida no esta configurada.</p>
            </div>
        </div>
        <br />
        <?php
    } else {
        $strQuery = "SELECT * FROM cllg_contab_ciclo WHERE activo = '1' AND fk_empresa = '{$empresa}'";
        $qTMP = $db->query($strQuery);
        $intNumRows = $db->num_rows;
        $rTMP = $db->fetch_array($qTMP);
        $intCiclo = $rTMP["codigo"];
        $db->free_result($qTMP);
        if ($intNumRows > 0) {
            $strQuery = "INSERT INTO cllg_contab_ajuste
                         (id, fecha, monto, ciclo, descripcion)
                         VALUES
                         (NULL, '{$fecha}', {$valor}, '{$intCiclo}', '{$concepto}')";
            $db->query($strQuery);
            $intAjuste = mysql_insert_id($db->link_id);

            //GENERA CIERRE
            $usr = $_SESSION[USUARIO]["usuario"];
            $db->query("insert into cllg_academico_cobros_cierre(FECHA,USUARIO,FK_AJUSTE) 
                            values( CURDATE(),'$usr',$intAjuste) ");

            if ($intAjuste > 0) {
                while ($arrPost = each($_POST)) {
                    $arrExplode = explode("_", $arrPost["key"]);
                    if ($arrExplode[0] == "hdnCuenta" && $arrPost["value"] > 0) {

                        $debe = getParam("txtDebe_" . $arrExplode[1]);
                        $haber = getParam("txtHaber_" . $arrExplode[1]);
                        if ($debe > 0 && $haber == 0) {
                            $monto = $debe;
                            $debe = 1;
                            $haber = 0;
                        } else if ($debe == 0 && $haber > 0) {
                            $monto = $haber;
                            $debe = 0;
                            $haber = 1;
                        }
                        $strQuery = "INSERT INTO cllg_contab_cuenta_ajuste
                                     (cuenta, debe, haber, monto, ajuste)
                                     VALUES
                                     ('{$arrPost["value"]}', '{$debe}', '{$haber}', '{$monto}', '{$intAjuste}')";
                        $db->query($strQuery);
                    }
                }
                reset($_POST);
                while ($arrTMP = each($_POST)) {
                    $arrExplode = explode("_", $arrTMP["key"]);
                    if ($arrExplode[0] == "sltCuenta") {
                        $intCuenta = ( isset($_POST["sltCuenta_{$arrExplode[1]}"]) ) ? $_POST["sltCuenta_{$arrExplode[1]}"] : 0;
                        $sinMonto = ( isset($_POST["hdnMonto_{$arrExplode[1]}"]) ) ? mround($_POST["hdnMonto_{$arrExplode[1]}"], 2) : 0;

                        $db->query("INSERT INTO cllg_bnc_docto_solicitud
                                        (FECHA, MONTO, TIPO, NOMBRE, CONCEPTO, ESTADO, FK_CUENTA, MODULO) 
                                    VALUES 
                                        ('{$fecha}', '{$sinMonto}', '2', '', '{$concepto}', '4', '{$intCuenta}', 'ACADEMICO')");
                        $intSolicitud = mysql_insert_id($db->link_id);
                        $intNota = fntAcademicoCobrosCierreSiguienteNota($db, "1");
                        $strNotas .= ( empty($strNotas)) ? "" : ", ";
                        $strNotas .= $intNota;

                        $db->query("INSERT INTO cllg_bnc_notas(FK_CUENTA, TIPO, ID, MONTO, FECHA, CONCEPTO, ESTADO, FK_SOLICITUD, FK_AJUSTE)
                                    VALUES ('{$intCuenta}', '1', '{$intNota}', '{$sinMonto}', '{$fecha}', '{$concepto}', '1', '{$intSolicitud}', '{$intAjuste}')");
                        $db->query("UPDATE cllg_academico_pagos 
                                SET ESTADO = 'CERRADO', FK_AJUSTE = '{$intAjuste}', FK_NC = '{$intNota}' ,
                                FK_CIERRE=(select max(ID) from cllg_academico_cobros_cierre), USUARIO_CIERRE='$usr'
                                WHERE ID IN ({$intPagos})");

                        //guarda la referencia del cierre y nota bancaria
                        $db->query("insert into cllg_academico_cobros_cierrenota 
                            values((select max(ID) from cllg_academico_cobros_cierre),$intNota ) ");
                    }
                    if ($arrExplode[0] == "chkPagoID") {
                        $strCobros = "";
                        $strCobros .= ( empty($strCobros)) ? "" : ",";
                        //$strCobros .= $_POST["hdnCobroID_{$arrExplode[1]}"];
                        $strCobros .= $cobros[$arrExplode[1]];
                    }
                }
                ?>  
                <div class="ui-widget" style="border: 0px solid white; width: 900px; height: auto; vertical-align: bottom;" >
                    <div class="ui-state-highlight ui-corner-all" style="margin-top: 0px; padding: 0pt 0.7em; height: auto; width: 320px;">
                        <p><span class="ui-icon ui-icon-info" style="float: left; margin-right: 0.3em;"></span>
                            Partida ingresada No. <?php print $intAjuste; ?><br>
                            Notas de credito ingresadas No. <?php print $strNotas; ?></p>
                    </div>
                </div>
                <?php
            }
        }
    }
}

function fntAcademicoCobrosCierreSiguienteNota($db, $intTipo) {
    $intNota = 0;
    $strQuery = "SELECT  MAX(ID) AS ID
                FROM    cllg_bnc_notas
                WHERE   cllg_bnc_notas.TIPO = '{$intTipo}'";
    $qTMP = $db->query($strQuery);
    while ($rTMP = $db->fetch_array($qTMP)) {
        $intNota = $rTMP["ID"] + 1;
    }
    $db->free_result($qTMP);

    return $intNota;
}

function mround($number, $precision = 0) {

    $precision = ($precision == 0 ? 1 : $precision);
    $pow = pow(10, $precision);

    $ceil = ceil($number * $pow) / $pow;
    $floor = floor($number * $pow) / $pow;

    $pow = pow(10, $precision + 1);

    $diffCeil = $pow * ($ceil - $number);
    $diffFloor = $pow * ($number - $floor) + ($number < 0 ? -1 : 1);

    if ($diffCeil >= $diffFloor)
        return $floor;
    else
        return $ceil;
}
?>